<template>
  <div class="practice-container">
    <!-- 顶部进度区域 -->
    <div class="header-section">
      <div class="header-content">
        <div class="progress-area">
          <el-button type="text" @click="$router.push('/home/learning')" class="back-btn">
            <i class="el-icon-arrow-left"></i>
            返回
          </el-button>

          <div class="question-info">
            <span class="subject-tag">{{ getSubjectName(currentSubject) }}</span>
            <span class="question-count">
              题目：{{ currentQuestionIndex + 1 }}/{{ questions.length }}
            </span>
          </div>

          <div class="progress-section">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
            </div>
            <span class="progress-text">{{ Math.round(progressPercentage) }}%</span>
          </div>
        </div>

        <!-- 顶部标签栏 -->
        <div class="tabs-section">
          <div class="tab-buttons">
            <button v-for="tab in tabs" :key="tab.key" :class="['tab-btn', { active: activeTab === tab.key }]"
              @click="activeTab = tab.key">
              {{ tab.label }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-loading v-loading="loading" element-loading-text="正在加载题目..." element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)" />
      </div>

      <!-- 题目显示区域 -->
      <div v-else-if="questions.length > 0" class="question-section">
        <!-- 综合考察标题 -->
        <div class="question-header">
          <h3 class="question-title">{{ getQuestionTypeDisplay(currentQuestion.question_type) }}</h3>
          <div class="question-meta">
            <span class="difficulty-tag" :class="getDifficultyClass(currentQuestion.difficulty)">
              难度：{{ getDifficultyText(currentQuestion.difficulty) }}
            </span>
            <span class="subject-info">科目：{{ getSubjectName(currentQuestion.subject) }}</span>
          </div>
        </div>

        <!-- 题目内容 -->
        <!-- 题目内容 -->
        <div class="question-content">
          <div class="question-text" v-html="currentQuestion.content"></div>
          <!-- 如果有图片字段则显示图片 -->
          <div v-if="currentQuestion.image" style="margin-top: 16px;">
            <img :src="currentQuestion.image" alt="题目图片" style="max-width: 100%; border-radius: 8px;" />
          </div>
          <!-- 选择题选项 -->
          <div class="options-container">
            <div v-for="(option, optionKey) in currentQuestion.options" :key="optionKey"
              :class="['option-item', getOptionClass(optionKey)]" @click="selectOption(optionKey)">
              <div class="option-label">{{ optionKey }}</div>
              <div class="option-content">{{ option }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="暂无题目数据">
          <el-button type="primary" @click="loadQuestions">重新加载</el-button>
        </el-empty>
      </div>

      <!-- 右侧答题卡 -->
      <div v-if="questions.length > 0" class="answer-card">
        <div class="card-header">
          <h4>答题卡</h4>
          <p class="card-subtitle">已答 {{ answeredCount }}/{{ questions.length }}</p>
        </div>

        <div class="answer-grid">
          <div v-for="(answer, index) in answerSheet" :key="index" :class="['answer-cell', getAnswerCellClass(index)]"
            @click="jumpToQuestion(index)">
            {{ index + 1 }}
          </div>
        </div>

        <!-- 答题统计 -->
        <div class="answer-stats">
          <div class="stat-item">
            <span class="stat-label">已答题</span>
            <span class="stat-value answered">{{ answeredCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">未答题</span>
            <span class="stat-value unanswered">{{ questions.length - answeredCount }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作区域 -->
    <div class="footer-section">
      <div class="footer-content">
        <div class="action-buttons-left">
          <el-button @click="toggleFavorite" :type="isFavorite ? 'primary' : 'default'">
            {{ isFavorite ? '已收藏' : '收藏' }}
          </el-button>
          <el-button @click="reportError">纠错</el-button>
        </div>

        <div class="navigation-buttons">
          <el-button @click="previousQuestion" :disabled="currentQuestionIndex === 0">
            上一题
          </el-button>
          <el-button @click="nextQuestion" :disabled="currentQuestionIndex === questions.length - 1">
            下一题
          </el-button>
        </div>

        <div class="action-buttons-right">
          <el-button type="primary" @click="submitAnswer" :disabled="selectedOption === null">
            提交答案
          </el-button>
        </div>
      </div>
    </div>

    <!-- 答案解析弹窗 -->
    <el-dialog v-model="showAnalysis" title="答案解析" width="60%" :show-close="true">
      <div class="analysis-content">
        <div class="result-header">
          <div v-if="isAnswerCorrect" class="correct-result">
            <i class="el-icon-success"></i>
            <span>回答正确！</span>
          </div>
          <div v-else class="wrong-result">
            <i class="el-icon-error"></i>
            <span>回答错误</span>
          </div>
        </div>

        <div class="correct-answer">
          <h4>正确答案：{{ currentQuestion.correctAnswer }}</h4>
        </div>

        <div class="analysis-text">
          <h5>解析：</h5>
          <p>{{ currentQuestion.analysis || '暂无解析' }}</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAnalysis = false">关闭</el-button>
          <el-button type="primary" @click="goToNextQuestion" v-if="currentQuestionIndex < questions.length - 1">
            下一题
          </el-button>
          <el-button type="success" @click="finishPractice" v-else>
            完成练习
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 纠错弹窗 -->
    <el-dialog v-model="showErrorReport" title="题目纠错" width="50%">
      <el-form :model="errorReport" label-width="80px">
        <el-form-item label="错误类型">
          <el-select v-model="errorReport.type" placeholder="请选择错误类型">
            <el-option label="题目内容错误" value="content"></el-option>
            <el-option label="选项错误" value="options"></el-option>
            <el-option label="答案错误" value="answer"></el-option>
            <el-option label="解析错误" value="analysis"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细描述">
          <el-input v-model="errorReport.description" type="textarea" :rows="4" placeholder="请详细描述发现的问题..."></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="errorReport.contact" placeholder="可选，方便我们联系您"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showErrorReport = false">取消</el-button>
          <el-button type="primary" @click="submitErrorReport">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 完成练习弹窗 -->
    <el-dialog v-model="showFinishDialog" title="练习完成" width="40%" :show-close="false">
      <div class="finish-content">
        <div class="finish-stats">
          <h3>练习统计</h3>
          <div class="stats-grid">
            <div class="stat-box">
              <div class="stat-number">{{ questions.length }}</div>
              <div class="stat-label">总题数</div>
            </div>
            <div class="stat-box">
              <div class="stat-number">{{ answeredCount }}</div>
              <div class="stat-label">已答题</div>
            </div>
            <div class="stat-box">
              <div class="stat-number">{{ correctCount }}</div>
              <div class="stat-label">正确数</div>
            </div>
            <div class="stat-box">
              <div class="stat-number">{{ Math.round((correctCount / answeredCount) * 100) || 0 }}%</div>
              <div class="stat-label">正确率</div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="restartPractice">重新开始</el-button>
          <el-button type="primary" @click="backToHome">返回练习中心</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'


export default {
  name: 'Practice408',
  setup() {
    const route = useRoute()
    const router = useRouter()

    const userStore = useUserStore()






    // 响应式数据
    const questions = ref([])
    const currentQuestionIndex = ref(0)
    const currentSubject = ref('计算机科学')
    const activeTab = ref('做题区')
    const selectedOption = ref(null)
    const showAnalysis = ref(false)
    const showErrorReport = ref(false)
    const showFinishDialog = ref(false)
    const loading = ref(false)
    const isFavorite = ref(false)
    const startTime = ref(Date.now()) // 进入页面时记录
    const duration = ref(0)

    // 答题记录
    const answerSheet = ref([])
    const correctAnswers = ref([])

    // 标签数据
    const tabs = [
      { key: '做题区', label: '做题区' },

    ]

    // 纠错表单
    const errorReport = reactive({
      type: '',
      description: '',
      contact: '' // 新增联系方式
    })

    // 计算属性
    const currentQuestion = computed(() => {
      if (questions.value.length === 0) return {}
      const question = questions.value[currentQuestionIndex.value]

      // 解析JSON格式的答案数据
      let parsedAnswer = {}
      try {
        parsedAnswer = typeof question.answer === 'string'
          ? JSON.parse(question.answer)
          : question.answer
      } catch (error) {
        console.error('解析答案JSON失败:', error)
        parsedAnswer = { correct: 'A', options: {} }
      }

      return {
        ...question,
        options: parsedAnswer.options || {},
        correctAnswer: parsedAnswer.correct || 'A'
      }
    })

    const progressPercentage = computed(() => {
      if (questions.value.length === 0) return 0
      return ((currentQuestionIndex.value + 1) / questions.value.length) * 100
    })

    const answeredCount = computed(() => {
      return answerSheet.value.filter(answer => answer !== null && answer !== undefined).length
    })

    const correctCount = computed(() => {
      return correctAnswers.value.filter(Boolean).length
    })

    const isAnswerCorrect = computed(() => {
      return selectedOption.value === currentQuestion.value.correctAnswer
    })

    // API 调用函数
    const api = {
      // 获取全部题目
      getQuestions: () => axios.get('/question/all'),

      // 根据知识点获取题目
      getQuestionsByPoint: (pointId) => axios.get(`/question/getbypid?pointId=${pointId}`),

      // 根据ID获取单个题目
      getQuestionById: (questionId) => axios.get(`/question/get?questionId=${questionId}`)
      
      
    }

    // 工具函数
    const getSubjectName = (subject) => {
      const subjectMap = {
        'DS': '数据结构',
        'OS': '操作系统',
        'CN': '计算机网络',
        'DB': '数据库'
      }
      return subjectMap[subject] || subject
    }

    const getQuestionTypeDisplay = (questionType) => {
      // 根据题型编码解析显示名称
      const typeMap = {
        'CS01': '单选题',
        'CS02': '多选题',
        'CS03': '填空题',
        'CS04': '简答题'
      }
      return typeMap[questionType] || '选择题'
    }

    const getDifficultyText = (difficulty) => {
      const difficultyMap = {
        1: '基础',
        2: '简单',
        3: '中等',
        4: '困难',
        5: '有挑战性'
      }
      return difficultyMap[difficulty] || '中等'
    }

    const getDifficultyClass = (difficulty) => {
      const classMap = {
        1: 'difficulty-easy',
        2: 'difficulty-simple',
        3: 'difficulty-medium',
        4: 'difficulty-hard',
        5: 'difficulty-extreme'
      }
      return classMap[difficulty] || 'difficulty-medium'
    }

    const getOptionClass = (optionKey) => {
      const classes = []
      if (selectedOption.value === optionKey) {
        classes.push('selected')
      }
      if (showAnalysis.value) {
        if (optionKey === currentQuestion.value.correctAnswer) {
          classes.push('correct')
        } else if (selectedOption.value === optionKey && optionKey !== currentQuestion.value.correctAnswer) {
          classes.push('wrong')
        }
      }
      return classes
    }

    const getAnswerCellClass = (index) => {
      const answer = answerSheet.value[index]
      if (answer === null || answer === undefined) {
        return index === currentQuestionIndex.value ? 'current' : 'empty'
      }
      return correctAnswers.value[index] ? 'correct' : 'wrong'
    }

    // 数据加载
    const loadQuestions = async () => {
      try {
        loading.value = true
        let response

        // 检查路由参数，决定加载方式
        const pointId = route.query.pointId
        const subject = route.query.subject

        if (pointId) {
          response = await api.getQuestionsByPoint(pointId);
        } else {
          response = await api.getQuestions();
        }

        const allQuestions = response.data?.data || response.data || []
        questions.value = allQuestions // 不做截取，全部显示

        // 初始化答题卡
        answerSheet.value = new Array(questions.value.length).fill(null)
        correctAnswers.value = new Array(questions.value.length).fill(false)

        if (questions.value.length === 0) {
          ElMessage.warning('暂无题目数据')
        } else {
          // 根据第一题的科目设置当前科目
          if (questions.value[0]?.subject) {
            currentSubject.value = questions.value[0].subject; // 只保存编码
          }
        }
      } catch (error) {
        console.error('加载题目失败:', error)
        ElMessage.error('加载题目失败，请重试')
      } finally {
        loading.value = false
      }
      console.log('questions.value[0].subject:', questions.value[0]?.subject);
      console.log('currentSubject.value:', currentSubject.value);
      console.log('questions.value[0]:', questions.value[0]);
    }

    // 题目操作
    const selectOption = (optionKey) => {
      selectedOption.value = optionKey
    }

    const submitAnswer = async () => {
      if (selectedOption.value === null) {
        ElMessage.warning('请先选择答案')
        return
      }

      // 保存答案到答题卡
      answerSheet.value[currentQuestionIndex.value] = selectedOption.value
      correctAnswers.value[currentQuestionIndex.value] = isAnswerCorrect.value

      // 可以在这里添加提交答案到服务器的逻辑
      try {
        // await api.submitAnswer({
        //   questionId: currentQuestion.value.question_id,
        //   answer: selectedOption.value,
        //   isCorrect: isAnswerCorrect.value
        // })
      } catch (error) {
        console.error('提交答案失败:', error)
      }

      showAnalysis.value = true
    }

    const jumpToQuestion = (index) => {
      if (index === currentQuestionIndex.value) return

      currentQuestionIndex.value = index
      selectedOption.value = answerSheet.value[index]
    }

    const previousQuestion = () => {
      if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--
        selectedOption.value = answerSheet.value[currentQuestionIndex.value]
      }
    }

    const nextQuestion = () => {
      if (currentQuestionIndex.value < questions.value.length - 1) {
        currentQuestionIndex.value++
        selectedOption.value = answerSheet.value[currentQuestionIndex.value]
      }
    }

    const goToNextQuestion = () => {
      showAnalysis.value = false
      if (currentQuestionIndex.value < questions.value.length - 1) {
        nextQuestion()
      }
    }

    // 功能操作
    const showHint = () => {
      if (currentQuestion.value.hint) {
        ElMessage.info(currentQuestion.value.hint)
      } else {
        ElMessage.info('暂无提示信息')
      }
    }

    // 收藏相关方法（根据后端接口路径调整）
    const addToFavorites = async () => {
      try {
        const res = await axios.post('/add', {
          userId: userStore.userInfo.userId,
          questionId: currentQuestion.value.questionId,
        });
        if (res.data === '该题已收藏') {
          ElMessage.warning('该题已收藏');
        } else {
          ElMessage.success('收藏成功');
        }
        isFavorite.value = true;
      } catch (error) {
        ElMessage.error('收藏失败');
        isFavorite.value = false;
      }
    };

    const removeFromFavorites = async () => {
      try {
        await axios.delete('/delete', {
          data: {
            userId: userStore.userInfo.userId,
            questionId: currentQuestion.value.questionId,
          }
        });
        ElMessage.success('已取消收藏');
        isFavorite.value = false;
      } catch (error) {
        ElMessage.error('取消收藏失败');
        isFavorite.value = true;
      }
    };

    const checkFavoriteStatus = async () => {
      try {
        const res = await axios.get('/check', {
          params: {
            userId: userStore.userInfo.userId,
            questionId: currentQuestion.value.questionId
          }
        });
        isFavorite.value = res.data === true;
      } catch (error) {
        isFavorite.value = false;
      }
    };

    const toggleFavorite = () => {
      if (isFavorite.value) {
        removeFromFavorites();
      } else {
        addToFavorites();
      }
    };

    // 监听题目变化，自动检查收藏状态
    watch(currentQuestionIndex, () => {
      selectedOption.value = answerSheet.value[currentQuestionIndex.value];
      checkFavoriteStatus();
    })

    // 纠错弹窗显示方法
    const reportError = () => {
      showErrorReport.value = true;
    }

    // 提交纠错报告
    const submitErrorReport = async () => {
      if (!errorReport.type || !errorReport.description) {
        ElMessage.warning('请填写完整的错误信息')
        return
      }
      try {
        // 组装反馈数据，字段与后端 Feedback_Info 实体一致
        const feedbackData = {
          feedbackId: 2, // 写定为2
          userId: userStore.userInfo?.userId || null,
          courseId: route.query.courseId || null, // 如有课程ID
          questionId: currentQuestion.value.questionId || currentQuestion.value.question_id || null,
          feedbackType: 2, // feedback_type写死为2
          content: errorReport.description,
          contact: errorReport.contact || userStore.userInfo?.email || userStore.userInfo?.phone || null,
          status: 0
        }
        await axios.post('/feedbacks/add', feedbackData)
        ElMessage.success('纠错报告已提交，感谢您的反馈！')
        showErrorReport.value = false
        // 重置表单
        errorReport.type = ''
        errorReport.description = ''
        errorReport.contact = ''
      } catch (error) {
        console.error('提交纠错报告失败:', error)
        ElMessage.error('提交失败，请重试')
      }
    }

    // 练习结束
    const finishPractice = async () => {
      showAnalysis.value = false
      showFinishDialog.value = true
      duration.value = Math.floor((Date.now() - startTime.value) / 1000)

      try {
        // 1. 获取用户信息和练习数据
        console.log('第一题完整数据:', questions.value[0])
    console.log('题目字段名:', Object.keys(questions.value[0] || {}))
        const userId = userStore.userInfo.userId
        const subjectToCourseMap = {
        'DS': 1,     // 数据结构
        'OS': 2,      // 操作系统 
        'CS': 3,     // 计组
        'CN': 4,     // 计算机网络
      }
      const courseId = subjectToCourseMap[currentSubject.value]
        const pointId = questions.value[0]?.pointId || route.query.pointId || null
        const questionCount = questions.value.length
        const correctCount = correctAnswers.value.filter(Boolean).length

        // 2. 先添加练习记录
        const practiceRecord = {
          userId,
          courseId,
          pointId,
          questionCount,
          correctCount,
          duration: duration.value
        }

        // 添加练习记录并等待响应
        const practiceRes = await axios.post('/userPractices/add', practiceRecord)

        // 从响应中获取新的 practice_id
        const practiceId = practiceRes.data
        console.log('获取到新的 practice_id:', practiceId)

        console.log('practiceRes完整结构:', {
          status: practiceRes.status,
          statusText: practiceRes.statusText,
          data: practiceRes.data,
          headers: practiceRes.headers

        })


        if (!practiceId) {
          throw new Error('未获取到练习记录ID')
        }

        // 3. 使用新的 practice_id 添加练习详情
        for (let i = 0; i < questions.value.length; i++) {
          // 插入练习详情
          const detailPayload = {
            practiceId: practiceId,
            questionId: questions.value[i].questionId,
            isCorrect: correctAnswers.value[i] ? 1 : 0,
            userAnswer: answerSheet.value[i] || ''
          }
          try {
            await axios.post('/practiceDetail/add', detailPayload)
          } catch (err) {
            console.error(`保存第${i + 1}题详情失败:`, err)
          }

          // 插入错题记录（只针对答错的题）
          if (!correctAnswers.value[i]) {
            const wrongPayload = {
              userId: userStore.userInfo.userId,
              questionId: questions.value[i].questionId,
              courseId: questions.value[i].courseId || courseId, // 使用备用值
              pointId: questions.value[i].pointId || pointId,    // 使用备用值
              sourceType: 1,
              sourceId: practiceId,
              wrongCount: 1,
              lastWrongTime: new Date(),
              isMastered: 0,
              isDeleted: 0
            }

            console.log('准备插入错题记录:', wrongPayload) // 添加调试日志

            try {
              await axios.post('/wrongquestions/insert', wrongPayload)
            } catch (err) {
              console.error(`插入第${i + 1}题错题失败:`, err)
              console.error('错误详情:', err.response?.data) // 查看服务器返回的具体错误
            }
          }
        }

        ElMessage.success('练习记录保存成功！')
      } catch (error) {
        console.error('保存练习记录失败:', error)
        ElMessage.error('保存练习记录失败：' + error.message)
      }
    }





    // 额外的调试函数：用于测试后端响应格式
    const debugPracticeResponse = async () => {
      try {
        const testRecord = {
          userId: userStore.userInfo.userId,
          courseId: 1,
          pointId: null,
          questionCount: 1,
          correctCount: 1,
          duration: 60
        }

        const response = await axios.post('/userPractices/add', testRecord)
        console.log('=== 后端响应调试 ===')
        console.log('response:', response)
        console.log('response.data:', response.data)
        console.log('response.data 类型:', typeof response.data)
        console.log('response.data JSON:', JSON.stringify(response.data, null, 2))

      } catch (error) {
        console.error('调试请求失败:', error)
      }
    }

    // 可选：数据验证辅助函数
    const validateQuestionsData = () => {
      const missingIds = []
      questions.value.forEach((question, index) => {
        if (!question.questionId) {  // 修正为questionId
          missingIds.push(index + 1)
        }
      })

      if (missingIds.length > 0) {
        console.error('以下题目缺少questionId:', missingIds)
        ElMessage.error(`题目 ${missingIds.join(', ')} 缺少ID，无法提交练习记录`)
        return false
      }

      return true
    }


    // 改进版本：在开始练习前验证数据
    const startPracticeWithValidation = () => {
      if (!validateQuestionsData()) {
        return false
      }
      // 其他初始化逻辑...
      return true
    }

    const restartPractice = () => {
      showFinishDialog.value = false
      currentQuestionIndex.value = 0
      selectedOption.value = null
      answerSheet.value = new Array(questions.value.length).fill(null)
      correctAnswers.value = new Array(questions.value.length).fill(false)
    }

    const backToHome = () => {
      // 跳转到学习中心首页
      router.push('/home/learning')
    }

    // 监听题目变化，重置选中状态
    watch(currentQuestionIndex, () => {
      selectedOption.value = answerSheet.value[currentQuestionIndex.value]
    })

    // 生命周期
    onMounted(() => {
      loadQuestions()
    })

    // 纠错类型映射函数
    const getErrorTypeCode = (type) => {
      switch (type) {
        case 'content': return 1;      // 题目内容错误
        case 'options': return 2;      // 选项错误
        case 'answer': return 3;       // 答案错误
        case 'analysis': return 4;     // 解析错误
        default: return 0;
      }
    }

    return {
      // 数据
      questions,
      currentQuestionIndex,
      currentSubject,
      activeTab,
      selectedOption,
      showAnalysis,
      showErrorReport,
      showFinishDialog,
      loading,
      isFavorite,
      answerSheet,
      correctAnswers,
      tabs,
      errorReport,
      // 计算属性
      currentQuestion,
      progressPercentage,
      answeredCount,
      correctCount,
      isAnswerCorrect,
      // 方法
      loadQuestions,
      selectOption,
      getSubjectName,
      getQuestionTypeDisplay,
      getDifficultyText,
      getDifficultyClass,
      getOptionClass,
      getAnswerCellClass,
      jumpToQuestion,
      submitAnswer,
      previousQuestion,
      nextQuestion,
      goToNextQuestion,
      showHint,
      addToFavorites,
      removeFromFavorites,
      checkFavoriteStatus,
      toggleFavorite,
      reportError,
      submitErrorReport,
      finishPractice,
      restartPractice,
      backToHome
    }
  }
}
</script>

<style scoped>
/* 美观化整体页面风格，优化配色、卡片、按钮、阴影、圆角、响应式等 */
.practice-container {
  background: linear-gradient(135deg, #f9f8ff 0%, #e3f0ff 100%);
  min-height: 100vh;
  padding: 32px 0 32px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 顶部区域 */
.header-section {
  width: 90%;
  max-width: 1100px;
  margin-bottom: 18px;
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(99, 143, 255, 0.10);
  padding: 18px 32px 12px 32px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.header-content {
  padding: 16px 24px;
}

.progress-area {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  color: #4b6fff;
  font-weight: bold;
  font-size: 16px;
}

.question-info {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.subject-tag {
  background: #e3f0ff;
  color: #4b6fff;
  border-radius: 8px;
  padding: 2px 10px;
  margin-right: 10px;
  font-size: 15px;
}

.progress-section {
  display: flex;
  align-items: center;
}

.progress-bar {
  width: 120px;
  height: 10px;
  background: #e3e9f7;
  border-radius: 6px;
  margin-right: 8px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4b6fff 0%, #7ecbff 100%);
  border-radius: 6px;
  transition: width 0.3s;
}

.progress-text {
  color: #4b6fff;
  font-size: 14px;
  font-weight: 500;
}

.tabs-section {
  margin-top: 10px;
}

.tab-buttons {
  display: flex;
  gap: 12px;
}

.tab-btn {
  background: #f4f7ff;
  border: none;
  border-radius: 8px 8px 0 0;
  padding: 8px 22px;
  font-size: 15px;
  color: #4b6fff;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}

.tab-btn.active {
  background: #4b6fff;
  color: #fff;
  font-weight: bold;
}

/* 主要内容区域 */
.main-content {
  width: 90%;
  max-width: 1100px;
  display: flex;
  gap: 32px;
  margin: 0 auto 24px auto;
  min-height: 480px;
}

.question-section {
  flex: 2;
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(99, 143, 255, 0.10);
  padding: 32px 32px 24px 32px;
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
  animation: fadeIn 0.3s ease-in;
}

.question-header {
  margin-bottom: 18px;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.question-title {
  font-size: 22px;
  font-weight: bold;
  color: #4b6fff;
  margin-bottom: 2px;
}

.question-meta {
  display: flex;
  gap: 18px;
  font-size: 14px;
  color: #888;
}

.difficulty-tag {
  padding: 2px 10px;
  border-radius: 8px;
  font-size: 13px;
  background: #f4f7ff;
  color: #4b6fff;
}

.difficulty-easy {
  background: #eaffea;
  color: #3bbd3b;
}

.difficulty-simple {
  background: #e3f7ff;
  color: #4b6fff;
}

.difficulty-medium {
  background: #fffbe3;
  color: #e6a23c;
}

.difficulty-hard {
  background: #ffeaea;
  color: #f56c6c;
}

.difficulty-extreme {
  background: #fbeaff;
  color: #a23cf6;
}

.question-content {
  margin-top: 10px;
  font-size: 17px;
  color: #222;
}

/* 选择题选项 */
.options-container {
  margin-top: 18px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 18px;
}

.option-item {
  background: #f4f7ff;
  border-radius: 10px;
  padding: 14px 18px;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s;
  box-shadow: 0 2px 8px 0 rgba(99, 143, 255, 0.06);
  animation: slideIn 0.3s ease-out;
}

.option-item.selected {
  border: 2px solid #4b6fff;
  background: #e3f0ff;
  color: #4b6fff;
}

.option-item.correct {
  border: 2px solid #3bbd3b;
  background: #eaffea;
  color: #3bbd3b;
}

.option-item.wrong {
  border: 2px solid #f56c6c;
  background: #ffeaea;
  color: #f56c6c;
}

/* 右侧答题卡 */
.answer-card {
  flex: 1;
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(99, 143, 255, 0.10);
  padding: 24px 18px 18px 18px;
  min-width: 220px;
  max-width: 260px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  margin-top: 0;
}

.card-header {
  margin-bottom: 10px;
  text-align: center;
}

.card-header h4 {
  font-size: 18px;
  color: #4b6fff;
  font-weight: bold;
}

.card-subtitle {
  font-size: 13px;
  color: #888;
}

.answer-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  margin-bottom: 18px;
}

.answer-cell {
  background: #f4f7ff;
  border-radius: 8px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 15px;
  color: #4b6fff;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s;
}

.answer-cell.current {
  border: 2px solid #4b6fff;
  background: #e3f0ff;
  color: #4b6fff;
}

.answer-cell.answered {
  background: #eaffea;
  color: #3bbd3b;
  border: 2px solid #3bbd3b;
}

.answer-cell.empty {
  background: #f4f7ff;
  color: #bbb;
}

.answer-cell.correct {
  background: #eaffea;
  color: #3bbd3b;
  border: 2px solid #3bbd3b;
}

.answer-cell.wrong {
  background: #ffeaea;
  color: #f56c6c;
  border: 2px solid #f56c6c;
}

.answer-stats {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 13px;
}

.stat-label {
  color: #888;
}

.stat-value.answered {
  color: #3bbd3b;
  font-weight: bold;
}

.stat-value.unanswered {
  color: #bbb;
}

/* 底部操作区域 */
.footer-section {
  width: 90%;
  max-width: 1100px;
  margin: 0 auto 18px auto;
  display: flex;
  justify-content: center;
}

.footer-content {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px 0 rgba(99, 143, 255, 0.08);
  padding: 18px 32px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 18px;
}

.action-buttons-left,
.action-buttons-right {
  display: flex;
  gap: 12px;
}

.navigation-buttons {
  display: flex;
  gap: 12px;
}

.el-button {
  border-radius: 8px !important;
  font-size: 15px !important;
  padding: 7px 22px !important;
  font-weight: 500;
}

/* 加载和空状态 */
.loading-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 弹窗样式 */
.el-dialog__header {
  background: linear-gradient(90deg, #e3f0ff 0%, #f9f8ff 100%);
  border-radius: 14px 14px 0 0;
}

.el-dialog__body {
  background: #f9f8ff;
}

.el-dialog__footer {
  background: #f4f7ff;
  border-radius: 0 0 14px 14px;
}

.analysis-content {
  padding: 18px 0;
}

.result-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.correct-result {
  color: #3bbd3b;
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 6px;
}

.wrong-result {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 6px;
}

.correct-answer h4 {
  color: #4b6fff;
  font-size: 16px;
  margin-bottom: 6px;
}

.analysis-text {
  background: #fff;
  border-radius: 10px;
  padding: 12px 18px;
  color: #333;
  font-size: 15px;
  margin-top: 8px;
}

.finish-content {
  padding: 18px 0 0 0;
}

.finish-stats {
  margin-bottom: 10px;
}

.stats-grid {
  display: flex;
  gap: 24px;
  justify-content: center;
  margin-top: 10px;
}

.stat-box {
  background: #f4f7ff;
  border-radius: 10px;
  padding: 18px 24px;
  text-align: center;
  min-width: 90px;
  box-shadow: 0 2px 8px 0 rgba(99, 143, 255, 0.06);
}

.stat-number {
  font-size: 22px;
  color: #4b6fff;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  color: #888;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 900px) {
  .main-content {
    flex-direction: column;
    gap: 18px;
  }

  .question-section,
  .answer-card {
    max-width: 100%;
    width: 100%;
  }

  .footer-section {
    max-width: 100%;
    width: 100%;
  }

  .footer-content {
    flex-direction: column;
    gap: 10px;
    padding: 14px 10px;
  }

  .answer-grid {
    grid-template-columns: repeat(5, 1fr);
  }
}

/* 动画效果 */
.question-section {
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.option-item {
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-10px);
  }

  to {
    opacity: 1;
    transform: translateX(0);
  }
}
</style>